<template>
  <div class="modifyCollectData">
    <!-- Cell 单元格组件 显示数据 -->
    <van-cell-group>
        <!-- 使用 title 插槽来自定义日期 -->
        <van-cell :value=date is-link @click="show=true">
            <template #title>
                <span class="custom-title">目标时间</span>
            </template>
        </van-cell>
        <!-- 使用 title 插槽来自定义标题 -->
        <van-cell
            v-if="!titleState"
            :value=title
            is-link
            @click="handleTitle"
        >
            <template #title>
                <span class="custom-title">目标标题</span>
            </template>
        </van-cell>
        <!-- 修改标题 -->
        <van-field
            v-if="titleState"
            v-model.trim="title"
            label="目标标题"
            placeholder="请输入目标标题"
            ref="titleRef"
            @blur="handleTitle"
        />
        <!-- 使用 title 插槽来自定义已完成 -->
        <van-cell
            v-if="!scheduleState"
            :value=Number(schedule).toFixed(2)
            is-link
            @click="handleSchedule"
        >
            <template #title>
                <span class="custom-title">已完成</span>
            </template>
        </van-cell>
        <!-- 修改已完成 -->
        <van-field
            v-if="scheduleState"
            v-model="schedule"
            type="number"
            label="已完成"
            placeholder="请输入已完成金额"
            ref="scheduleRef"
            @blur="handleSchedule"
        />
        <!-- 使用 title 插槽来自定义目标 -->
        <van-cell
            v-if="!moneyState"
            :value=money
            is-link
            @click="handleMoney"
        >
            <template #title>
                <span class="custom-title">目标金额</span>
            </template>
        </van-cell>
        <!-- 修改目标 -->
        <van-field
            v-if="moneyState"
            v-model="money"
            type="number"
            label="目标金额"
            placeholder="请输入目标金额"
            ref="moneyRef"
            @blur="handleMoney"
        />
        <!-- 备注 -->
        <van-field
            v-model.trim="message"
            rows="2"
            autosize
            label="备注"
            type="textarea"
            maxlength="50"
            placeholder="请输入备注"
            show-word-limit
        />
    </van-cell-group>
    <!-- Popup 弹出层组件 控制时间选择组件的弹出 -->
    <van-popup
        v-model="show"
        position="bottom"
        :style="{height:'38%'}"
    >
      <!-- DatetimePicker 时间选择组件 选择时间 -->
      <van-datetime-picker
        v-model="currentDate"
        type="date"
        title="修改时间"
        :min-date="minDate"
        :max-date="maxDate"
        @confirm="handleSure"
        @cancel="show = false"
      />
    </van-popup>
    <!-- Button 按钮组件 点击保存修改 -->
    <van-button
      type="primary"
      block
      color="#1989fa"
      @click="handleSave"
    >
      保存修改
    </van-button>
    <!-- Button 按钮组件 点击删除 -->
    <van-button
      type="primary"
      block
      plain
      color="#1989fa"
      @click="handleDelete"
    >
      删除
    </van-button>
  </div>
</template>

<script>
import Vue from 'vue'
import { Toast, Dialog } from 'vant'
Vue.use(Dialog)
Vue.use(Toast)
export default {
  name: 'modifyCollectData',
  // 获取选中项的数据
  created () {
    if (!this.$store.state.username) return
    // 获取当前账号的数据
    const collectData = this.$store.state.userInfo.filter(user => user.username === this.$store.state.username)[0].collectData
    this.data = collectData.filter(item => item.id === this.$route.params.id)[0]
    this.message = this.data.message
    this.date = this.data.date
    this.title = this.data.title
    this.schedule = this.data.schedule
    this.money = this.data.money
  },
  data () {
    /**
       * data 选中目标是数据
       * meesage 备注
       * minDate 最小时间选择
       * maxDate 最大时间选择
       * currentDate 点击默认时间
       * show 选择时间弹框
       * date 日期字符串
       * title 标题
       * schedule 已完成
       * money 金额
       * titleState 标题状态
       * scheduleState 已完成状态
       * moneyState 金额状态
       */
    return {
      data: {},
      message: '',
      minDate: new Date(2020, 0, 1),
      maxDate: new Date(2025, 10, 1),
      currentDate: new Date(),
      show: false,
      date: '',
      title: '',
      schedule: '',
      money: '',
      titleState: false,
      scheduleState: false,
      moneyState: false,
      timeout1: '',
      timeout2: '',
    }
  },
  methods: {
    // 选择时间点击确认时将数据保存
    handleSure (time) {
      this.date = time.toLocaleDateString()
      this.show = false
    },
    // 点击标题部分的文本和输入框状态交换
    handleTitle () {
      if (!this.title) {
        Toast.fail('标题不能为空')
        return
      }
      this.titleState = !this.titleState
      if (!this.titleState) return
      this.$nextTick(() => {
        this.$refs.titleRef.focus()
      })
    },
    // 点击已完成部分的文本和输入框状态交换
    handleSchedule () {
      if (!this.schedule) this.schedule = 0
      if (Number(this.schedule) >= Number(this.money)) this.schedule = this.money
      this.scheduleState = !this.scheduleState
      this.schedule = Math.abs(Number(this.schedule)).toFixed(2)
      if (!this.scheduleState) return
      this.$nextTick(() => {
        this.$refs.scheduleRef.focus()
      })
    },
    // 点击目标金额部分的文本和输入框状态交换
    handleMoney () {
      if (!this.money) {
        Toast.fail('目标金额\n不能为空')
        return
      }
      this.moneyState = !this.moneyState
      this.money = Math.abs(Number(this.money)).toFixed(2)
      if (!this.moneyState) return
      this.$nextTick(() => {
        this.$refs.moneyRef.focus()
      })
    },
    // 点击保存修改时
    handleSave () {
      // 当标题为空时
      if (!this.title) {
        Toast.fail('标题不能为空')
        return
      }
      // 当目标金额为空时
      if (!this.money) {
        Toast.fail('目标金额\n不能为空')
        return
      }
      // 向 vuex 传递数据
      this.$store.commit('handleModifyCollectData', {
        id: this.data.id,
        date: this.date,
        title: this.title,
        money: Number(this.money).toFixed(2),
        schedule: this.schedule,
        message: this.message,
      })
      // 提示添加成功
      Toast.success({
        message: '修改成功',
        forbidClick: true,
      })
      // 1 秒之后跳转到 collect 页面，提升用户体验
      this.timeout1 = setTimeout(() => {
        this.$router.push({
          name: 'collect',
        })
      }, 1000)
    },
    // 点击删除时
    handleDelete () {
      // 弹出询问确认删除
      Dialog.confirm({
        title: '删除',
        message: '确定要删除这个存钱目标吗?',
      })
        // 点击确认时
        .then(() => {
          this.$store.commit('handleDeltetCollectData', {
            id: this.$route.params.id,
          })
          // 提示删除成功
          Toast.success({
            message: '删除成功',
            forbidClick: true,
          })
          // 1 秒之后跳转到 collect 页面，提升用户体验
          this.timeout2 = setTimeout(() => {
            this.$router.push({
              name: 'collect',
            })
          }, 1000)
        })
        // 点击取消时
        .catch(() => {
        })
    },
  },
  beforeDestroy () {
    clearTimeout(this.timeout1)
    clearTimeout(this.timeout2)
  },
}
</script>

<style lang="less" scoped>
.custom-title {
    margin-right: 4px;
    vertical-align: middle;
}

.search-icon {
    font-size: 16px;
    line-height: inherit;
}

.message {
    width: 30%;
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
}
</style>
